<template>
  <div class="container">
    <div class="canvas" ref="canvas"></div>
  </div>
</template>

<script>
// 引入相关依赖
import BpmnModeler from 'bpmn-js/lib/Modeler'
import { xmlStr } from '@/mock/xmlStr' // 直接引用 xml格式
export default {
  name: 'basic',
  data () {
    return {
      bpmnModeler: null, // bpmn 建模器
      container: null,
      canvas: null
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      // 获取canvas的dom节点
      const canvas = this.$refs.canvas
      // 建模
      this.bpmnModeler = new BpmnModeler({
        container: canvas
      })
      this.createNewDiagram()
    },
    createNewDiagram () {
      // 将字符串转换成图显示出来
      try {
        const result = this.bpmnModeler.importXML(xmlStr)
        const { warnings } = result
        console.log(warnings)
        this.success()
      } catch (err) {
        console.log(err.message, err.warnings)
      }
    },
    success () {
      console.log('创建成功')
      this.addModelerListener()
      this.addEventBusListener()
    },
    // 监听 modeler
    addModelerListener () {
      const bpmnjs = this.bpmnModeler
      const that = this
      // 这里用 forEach 给 modeler 上添加要绑定的事件
      const events = ['shape.added', 'shape.move.end', 'shape.removed', 'connect.end', 'connect.move']
      events.forEach(event => {
        that.bpmnModeler.on (event, e => {
          console.log(event, e)
          const elementRegistry = bpmnjs.get('elementRegistry')
          const shape = e.element ? elementRegistry.get(e.element.id) : e.shape
          console.log(shape)
          // 通过监听事件判断操作方式
          if (event === 'shape.added') {
            console.log('新增了shape')
          } else if (event === 'shape.removed') {
            console.log('删除了shape')
          }
        })
      })
    },
    // 监听 element 
    addEventBusListener () {
      const eventBus = this.bpmnModeler.get('eventBus') // 需要使用 eventBus
      const eventType = ['element.click', 'element.changed'] // 需要监听的事件集合
      eventType.forEach (eventType => {
        eventBus.on(eventType, e => {
          if (!e || e.element.type == 'bpmn:Process') return // 这里根元素是 bpmn:Process
          console.log(e)
          const elementRegistry = this.bpmnModeler.get('elementRegistry')
          const shape = elementRegistry.get(e.element.id) // 传递 id 进去
          console.log(shape) // {Shape}
          console.log(e.element) // {Shape}
          console.log(JSON.stringify(shape) === JSON.stringify(e.element)) // true
        })
      })
    }
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
}
.canvas {
  width: 100%;
  height: 100%;
}
</style>